package com.rzico.sbl.ui.manager

import android.widget.ImageView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityCommonListBinding
import com.rzico.sbl.model.MasterData
import com.rzico.sbl.model.QRType
import com.rzico.sbl.ui.ScanActivity
import com.rzico.sbl.viewmodel.MasterViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.showOneHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import kotlin.text.orEmpty

class MasterActivity : BaseActivity(R.layout.activity_common_list) {

    private val mBinding by lazy { ActivityCommonListBinding.bind(getRootView()) }

    override fun getViewModel() = get<MasterViewModel>()

    override fun initData() {
        initTitle(title = "员工列表")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关员工信息！"
            }

            recycleList.also { layout ->
                layout.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                layout.addItemDecoration(SpaceTBDecoration())

                mAdapter = SlimAdapter.creator()
                    .register<MasterData>(R.layout.item_master_list) { jector, bean, index ->
                        jector.apply {
                            text(R.id.item_master_name, bean.name.orEmpty())
                            text(R.id.item_master_phone, bean.mobile.orEmpty())
                            text(R.id.item_master_job, bean.roleName.trimStart('.'))
                            text(R.id.item_master_shop, bean.shopName)
                            text(R.id.item_master_count, bean.shippingCard)
                            text(
                                R.id.item_master_mode,
                                bean.shippingMethod
                                    .joinToString("、") {
                                        when (it) {
                                            "fence" -> "区域配送"
                                            "binding" -> "指定派单"
                                            else -> ""
                                        }
                                    }
                            )
                            text(
                                R.id.item_master_status,
                                when (bean.status) {
                                    "rest" -> "休息中"
                                    "quit" -> "已离职"
                                    else -> ""
                                }
                            )

                            visibility(
                                R.id.item_master_mode_ll,
                                visibleValue { bean.shippingMethod.isNotEmpty() }
                            )

                            visibility(
                                R.id.item_master_count_ll,
                                visibleValue { "binding" in bean.shippingMethod }
                            )

                            with<ImageView>(R.id.item_master_img) {
                                it.loadCircleImage(bean.logo, R.mipmap.default_user)
                            }

                            clicked {
                                startActivityEx<MasterInfoActivity>("data" to bean)
                            }

                            longClicked {
                                deleteAdmin(bean, index)
                                true
                            }
                        }
                    }
                    .attachTo(layout)
            }
        }

        ivRight?.apply {
            setImageResource(R.mipmap.icon_manager16)
            setPadding(0, dp2px(15f), 0, dp2px(15f))
            visible()

            oneClick {
                startActivityEx<ScanActivity>(
                    "mode" to QRType.MASTER,
                    "from" to "master",
                    "status" to "list"
                )
            }
        }

        observe<String>("masterList") { updateList() }
    }

    /**
     * 删除优惠券
     */
    private fun deleteAdmin(item: MasterData, index: Int) {
        showHintDialog(
            title = "删除员工",
            hint = "确定要删除该员工吗？",
            sure = "删除",
            onSure = {
                item.shippingMethod
                    .isNotEmpty()
                    .conditionElse(
                        actionTrue = {
                            showOneHintDialog(
                                hint = "在执行删除员工操作时，请先清除该员工的派单模式后再执行删除操作。"
                            )
                        },
                        actionFalse = {
                            getViewModel()
                                .masterDel(item.id)
                                .bindLifeCycle(getLifecycleOwner())
                                .subscribeBySuccess(
                                    event = getViewModel(),
                                    onSuccess = {
                                        showToast("员工删除成功！")

                                        mList.removeAt(index)
                                        mAdapter.apply {
                                            notifyItemRemoved(index)
                                            notifyItemRangeChanged(index, mList.size - index)
                                        }

                                        mBinding
                                            .listLayout
                                            .emptyLayout
                                            .emptyView
                                            .isVisible = mList.isEmpty()
                                    }
                                )
                        }
                    )
            }
        )
    }

    /**
     * 员工列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .masterList(
                page = index,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}